//generator 生成器    iterator 迭代器 （迭代器有一个next方法，每次调用后都会返回value,done两个属性）
//类数组 有长度 有索引 是个对象 能被迭代

//给一个对象添加迭代器，可以使他被迭代
//这个函数执行后返回的是一个迭代器
let obj = {0:1,1:2,2:3,length:3,[Symbol.iterator]:function(){
  let self = this;
  let index = 0
  return {//迭代器 有next方法有value和done
    next(){
      return {value:self[index],done:index++ === self.length}
    }
  }
}}
function arg1(){
  let arr = [...obj];
  console.log(arr,Array.isArray(arr))
}
arg1(1,2,3,4,5)


let obj1 = {0:1,1:2,2:3,length:3,[Symbol.iterator]:function* (){
  //每次浏览器都会不停的调用next方法，把yield的结果作为值
  let index = 0
  while(index !== this.length){
    yield this[index++];
  }
}}

function arg2(){
  let arr = [...obj1];
  console.log(arr,Array.isArray(arr))
}
arg2(1,2,3,4,5)


//生成器会配合yield来使用，如果碰到yiled会暂停执行
function* read(){
  yield 1; //产出
  yield 2;
  yield 3
}
let it = read();
console.log(it.next())//{ value: 1, done: false }
console.log(it.next())//{ value: 2, done: false }
console.log(it.next())//{ value: 3, done: false }
console.log(it.next())//{ value: undefined, done: true }


//迭代
let mz = require('mz/fs');
function* read(){
  let r = yield mz.readFile('./promise/name.txt','utf8');
  let age = yield mz.readFile(r,'utf8');
  // return age;
  let e = yield [age]
  return e;
}
// let it1 = read();
// let {value,done} = it1.next();
// Promise.resolve(value).then(data=>{
//   let {value,done} = it1.next(data);
//   Promise.resolve(value).then(data=>{
//     let {value,done} = it1.next(data);
//     Promise.resolve(value).then(data=>{
//       console.log(data)
//     })
//   })
// })

function co(it){
  return new Promise((resolve,reject)=>{
    function next(val){
      let {value,done} = it.next(val);
      if(done){
        return resolve(value);
      }
      Promise.resolve(value).then(data=>{
        next(data);
      },reject)
    }
    next();
  })
}

//npm install co
// let co = require('co');
co(read()).then(data=>{
  console.log(data)
})